package com.ibm.spatiotemp.server.framework.handler;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.ibm.spatiotemp.server.datamodel.tenant.Tenant;
import com.ibm.spatiotemp.server.datamodel.tenant.TenantManager;
import com.ibm.spatiotemp.server.datasources.DataSource;
import com.ibm.spatiotemp.server.framework.request.Request;

public class RequestHandlerManager {
	public static Logger logger = Logger.getLogger(RequestHandlerManager.class);
	/*key = String tentid.String srcname*/
	private static ConcurrentHashMap<String,DataRequestHandler> datahandlerMap 
		= new ConcurrentHashMap<String, DataRequestHandler>();
	/*key = tenant id*/
	private static ConcurrentHashMap<String,TenantRequestHandler> tenanthandlerMap 
		= new ConcurrentHashMap<String, TenantRequestHandler>();
	
	private static boolean verifyTenant(String tentid){
		if(TenantManager.getTenantbyID(tentid)!=null){
			return true;
		}
		return false;
	}	
		
	public static DataRequestHandler getDataRequestHandler(String tentid, DataSource datasrc)
	{
		boolean tenantexist = verifyTenant(tentid);
		if(!tenantexist)
		{
			logger.error("tenant not found");
			return null;
		}
		String key = tentid+"."+datasrc.getSrcname();
		DataRequestHandler handler = datahandlerMap.get(key);
		if(handler==null)
		{
			handler = new DataRequestHandler(datasrc);
			datahandlerMap.put(key, handler);
		}
		return handler;
	}
	
	public static TenantRequestHandler getTenantRequestHandler(Request request)
	{
		String tentid = request.getTenantid();
		return getTenantRequestHandler(tentid);
	}
	
	public static DataRequestHandler getDataRequestHandler(Request request)
	{
		String tentid = request.getTenantid();
		String srcid = request.getSourceid();
		return getDataRequestHandler(tentid,srcid);
	}

	public static DataRequestHandler getDataRequestHandler(String tentid, String datasrc)
	{
		boolean tenantexist = verifyTenant(tentid);
		if(!tenantexist)
		{
			logger.error("tenant not found");
			return null;
		}
		Tenant tent = TenantManager.getTenantbyID(tentid);
		DataSource src = tent.getDataSourceBySourceName(datasrc);
		if(src==null)
		{
			logger.error(String.format("data source not found, datasrc=%s",datasrc));
			return null;
		}
		
		String key = tentid+"."+datasrc;
		DataRequestHandler handler = datahandlerMap.get(key);
		if(handler==null)
		{
			handler = new DataRequestHandler(src);
			datahandlerMap.put(key, handler);
		}
		return handler;
	}

	
	public static TenantRequestHandler getTenantRequestHandler(String tentid)
	{
		boolean tenantexist = verifyTenant(tentid);
		if(!tenantexist)
		{
			logger.error("tenant not found");
			return null;
		}

		String key = tentid;
		TenantRequestHandler handler = tenanthandlerMap.get(key);
		if(handler==null)
		{
			handler = new TenantRequestHandler();
			tenanthandlerMap.put(key, handler);
		}
		return handler;
	}
	
}
